package imganalysis;

import java.awt.image.SampleModel;
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.iterator.RandomIter;
import javax.media.jai.iterator.RandomIterFactory;

/**
 *
 * @author sheila
 */
public class BIC {
    PlanarImage pi;
    Pix aQuantizedPix[];
    int aiHistogram[];

    public BIC(PlanarImage pimg){            
        this.pi=pimg;
         SampleModel sm = pimg.getData().getSampleModel();
         int nbands = sm.getNumBands();
         int numcolors = 4;// em lugar de 255, so 4 cores para cada banda

         this.quantizy(numcolors);
         this.classification();
         this.computeHistogram(numcolors);
    }

      public void quantizy(int numcolors){
         RandomIter iterator = RandomIterFactory.create(pi, null);
         int n = 256; // posible values of Bright for an image 0-255 = 256 values
         int nbands = pi.getSampleModel().getNumBands();
         
         int range = n/numcolors;
         aQuantizedPix = new Pix[pi.getWidth()*pi.getHeight()];// cada banda pode ter valores entre 0 e 3

         for (int h = 0; h < pi.getHeight(); h++) {
            for (int w = 0; w < pi.getWidth(); w++) {
                int[] pixel = new int[nbands];
                iterator.getPixel(w, h, pixel);
                for(int band=0;band<nbands;band++){                    
                    pixel[band] = (int) Math.floor(pixel[band]/range);                    
                }
                aQuantizedPix[(h * pi.getWidth()) + w]=new Pix(w, h, pixel);             
             
            }
         }          
     }

     public void classification(){        
         int w,h;
         for (int i = 0; i < aQuantizedPix.length; i++) {
             w = i % pi.getWidth();
             h = (int) Math.floor( i / pi.getWidth() );
             Pix pix = aQuantizedPix[i];

             if ( w!=0  &&  w<pi.getWidth()-1  &&  h!=0  &&  h<pi.getHeight()-1 &&  //is Not on the border of the image
                     pix.compareBands(getPix(w-1,h)) && pix.compareBands(getPix(w+1,h)) &&
                     pix.compareBands(getPix(w,h-1)) && pix.compareBands(getPix(w-1,h+1)) )
                pix.isBorder=false;             
             else
                pix.isBorder=true;
         }

     }
     public void printImage(String strName, String strExtension){
         SampleModel sm = pi.getData().getSampleModel();

         for (int i = 0; i < aQuantizedPix.length; i++) {
             Pix p=aQuantizedPix[i];
             int val=255;
             if(p.isBorder) val=0;
             for (int band = 0; band < p.bands.length; band++)
                sm.setSample(p.x, p.y, band, val, pi.getData().getDataBuffer());
         }
         this.writeImage(pi, strName, strExtension);
     }

     public void writeHistogram(String pstrFile){
        try{
            FileWriter fstream = new FileWriter(pstrFile);
            BufferedWriter out = new BufferedWriter(fstream);
            for(int i=0;i<this.aiHistogram.length;i++){
                out.write(i+"\t"+this.aiHistogram[i]+"\n");
            }
            out.close();
        }catch (Exception e){ System.err.println("Error: " + e.getMessage());  }
             //JAI.create("filestore",pi, "/home/sheila/Pictures/florenciaazul.jpg","JPEG");
             //JAI.create("filestore",image,"a.tif","TIFF")
    }

     public int[] computeHistogram(int numcolors){
         int numTotalColors = (int)Math.pow(numcolors,3);
         aiHistogram=new int[numTotalColors*2];
         for (int i = 0; i < aQuantizedPix.length; i++) {
             Pix p=aQuantizedPix[i];              
             int val=0;//p.bands es siempre 1 2 1
             for (int j = 0; j < p.bands.length; j++) {
                 val += (int)Math.pow(numcolors,j) * p.bands[j];
                 
             }
             //creating two histograms one(border pixels) before another(interior pixels).             
             if(p.isBorder) aiHistogram[val]++;
             else           aiHistogram[val+numTotalColors]++;// after the 64 position
         }
         return aiHistogram;
     }


     public Pix getPix(int w, int h){
         return aQuantizedPix[ h*pi.getWidth() + w];
     }

     public int[] getHistogram(){
        return this.aiHistogram;
     }



     public void writeImage(PlanarImage pi, String name,String format){
         JAI.create("filestore",pi, name,"JPEG");
     }

     public void computeHistogram(PlanarImage pi,int band){
        RandomIter iterator = RandomIterFactory.create(pi, null);
        int[] pixel = new int[pi.getSampleModel().getNumBands()];
        int histogram[]=new int[256];
        for (int h = 0; h < pi.getHeight(); h++) {
            for (int w = 0; w < pi.getWidth(); w++) {
                iterator.getPixel(w, h, pixel);
                histogram[pixel[band]]++;
            }
         }
     }

     class Pix{
         int x;
         int y;
         int bands[]=new int[3];
         boolean isBorder; //border or interior

         public Pix(int px, int py, int pbands[]){
             this.x=px;
             this.y=py;
             //for (int i = 0; i < pbands.length; i++)                  this.bands[i] = pbands[i];
             this.bands=pbands;
         }
         public void printBands(){
             for (int i = 0; i < bands.length; i++) {
                 System.out.println("Banda "+i+ " ==> "+ bands[i]);
             }

         }
         public boolean compareBands(Pix p){
             int potherbands[] = p.bands;
             for (int i = 0; i < bands.length; i++) {
                 if(bands[i] != potherbands[i]){
                    return false;
                }
            }
            return true;
        }
     }
}
